package com.disktalk.web;

import java.util.List;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.disktalk.util.*;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.disktalk.entry.DiskFile;
import com.disktalk.entry.PageBean;
import com.disktalk.service.DiskFileService;

@Controller
@RequestMapping("/file")
public class FileController {

  private final Logger logger = LoggerFactory.getLogger(FileController.class);


  private final static String DES = "DES";
  private final static String key = "kxde!@#$%";//
  private final static String value = "cx";//

  @Autowired
  private DiskFileService diskFileService;

  private List<DiskFile> diskFileList;
  private DiskFile diskFile;
  private final static String viewName = "main_userCenter";

  private static String pageCode;
  private static HttpServletRequest request;
  private static HttpServletResponse response;
  private static PageBean pageBean;

  public HttpServletRequest getRequest() {
    return request;
  }

  @Resource
  public void setRequest(HttpServletRequest request) {
    this.request = request;
  }

  public HttpServletResponse getResponse() {
    return response;
  }

  @Resource
  public void setResponse(HttpServletResponse response) {
    this.response = response;
  }

  /**
   * 最新文件集合
   *
   * @param page
   * @param id
   * @return
   */
  @RequestMapping(value = "/list")
  public ModelAndView getNewFileList(HttpServletRequest req,@RequestParam(value = "page", required = false) String page) {
    ModelAndView mav = new ModelAndView();
    String fileFlag;
    Integer total;

    pageBean = getCurrentPage(page);
//    request.getSession().setAttribute("userName", userName);
//    String userName = getUserName();
    String userName = (String)req.getSession().getAttribute("userName");
    System.out.println("FileController=====userName===="+userName);
    fileFlag = "0"; // 最新文件集合
    total = diskFileService.getCount(fileFlag, userName);
    request.setAttribute("mainPage", "newFile.jsp");
    diskFileList = diskFileService.findDiskFileList(userName, "", pageBean, fileFlag);
    pageCode = PageUtil.genPaginationNoParam("/disktalk/file/list", total, pageBean.getPage(),
            pageBean.getPageSize());
    logger.info("===FileController====list===" + diskFileList + "   =====pageCode=" + pageCode);
    System.out.println("=========文件的大小：" + diskFileList.size() + "  total:" + total);
    mav.addObject("diskFileList", diskFileList);
    mav.addObject("pageCode", pageCode);
    mav.setViewName(viewName);
    return mav;
  }

  /**
   * 查找文件
   *
   * @param content
   * @return
   * @throws Exception
   */
  @RequestMapping(value = "/search")
  public ModelAndView getSearchList(@RequestParam(value = "content", required = false) String content,
                                    @RequestParam(value = "userName", required = false) String userName,
                                    @RequestParam(value = "page", required = false) String page) throws Exception {
    System.out.println("=========search=========" + content + "     userName:" + userName);
    ModelAndView mav = new ModelAndView();
    HttpSession session = request.getSession();
    boolean flag = false;
    pageBean = getCurrentPage(page);
    String type = request.getParameter("searchValue");
    System.out.println("===select====" + type);
    if (null == type || "".equals(type)) {
      type = "0";
    }
    Integer i = Integer.parseInt(type);
    if (2 == i) {// 用于区分查询共享文件和自身文件
      diskFileList = diskFileService.searchFile(userName, content, pageBean, type);// 查询分享文件
      String loginName = (String) session.getAttribute("loginName");
      //  if()
      request.setAttribute("mainPage", "shareFile.jsp");
      flag = true;
    } else if (1 == i) {
      request.setAttribute("mainPage", "recoveryList.jsp");
      diskFileList = diskFileService.searchFile(userName, content, pageBean, type);// 查询回收站文件
    } else {
      request.setAttribute("mainPage", "newFile.jsp");
      diskFileList = diskFileService.searchFile(userName, content, pageBean, type);// 查询自身文件
    }
    System.out.println("====diskFileList.size()======" + diskFileList.size());
    if (diskFileList.size() > 0) {
      Integer total = diskFileService.getCountByuNameOrfName(userName, content, type);
      if (flag) {
        pageCode = PageUtil.getSearchPage(
                "/disktalk/file/search?content=" + content + "&userName=" + userName + "&searchValue=" + type,
                total, pageBean.getPage(), pageBean.getPageSize());
      } else {
        pageCode = PageUtil.getSearchPage(
                "/disktalk/file/search?content=" + content + "&userName=" + userName + "&searchValue=" + type,
                total, pageBean.getPage(), pageBean.getPageSize());
      }
      mav.addObject("diskFileList", diskFileList);
      if (total > 10) {
        mav.addObject("pageCode", pageCode);
      }
    } else {
      request.setAttribute("mainPage", "info.jsp");
    }
    mav.setViewName(viewName);
    return mav;
  }

  /**
   * 下载分享文件密码判断
   *
   * @param ids
   * @return
   * @throws Exception
   */
  @RequestMapping(value = "/shareJudge")
  public ModelAndView shareJudge(@RequestParam(value = "ids", required = false) String ids) throws Exception {
    ModelAndView model = new ModelAndView();
    JSONObject result = new JSONObject();
    System.out.println("=========shareJudge=========" + ids);
    String pwd = request.getParameter("pwd");
    System.out.println("==pwd===" + pwd);
    diskFile = diskFileService.findDiskFile(ids);
    request.setAttribute("mainPage", "shareFile.jsp");
    model.setViewName(viewName);
    if (diskFile.getDownloadPwd().equals(pwd)) {
      result.put("result", true);
    } else {
      result.put("result", false);
    }
    ResponseUtil.write(result, response);
    return model;
  }

  /**
   * 文件分享
   *
   * @param ids
   * @return
   * @throws Exception
   */
  @RequestMapping(value = "/share")
  public ModelAndView shareFile(@RequestParam(value = "ids", required = false) String ids) throws Exception {
    ModelAndView mav = new ModelAndView();
    mav.setViewName(viewName);
    System.out.println("=========shareFile=========" + ids);
    JSONObject result = new JSONObject();
    String page = request.getParameter("page");
    String[] id = ids.split(",");
    int count = 0;
    System.out.println("分享文件的总数：" + id.length);
    for (int i = 0; i < id.length; i++) {
      System.err.println(id[i]);
      diskFile = diskFileService.findDiskFile(id[i]);
      String randomString = getRandomString(6);// 获得6位随机密码

      boolean flag = diskFileService.share(diskFile, randomString);
      if (flag) {
        count++;
        if (count == id.length) {
          request.setAttribute("mainPage", "shareFile.jsp");
          diskFileList = diskFileService.findDiskFileList("chen", "", pageBean, "2");
          result.put("result", "文件分享成功！！！");
        } else {
          request.setAttribute("mainPage", "newFile.jsp");
          diskFileList = diskFileService.findDiskFileList("chen", "", pageBean, "0");
          result.put("result", "文件分享失败！！！");
        }
        mav.addObject("diskFileList", diskFileList);
      }
    }
    ResponseUtil.write(result, response);
    return mav;
  }

  /**
   * 回收站文件列表
   *
   * @param page
   * @return
   */
  @RequestMapping(value = "/recoveryList")
  public ModelAndView getRecoveryFileList(@RequestParam(value = "page", required = false) String page) {
    System.out.println("=====getRecoveryFileList=====" + page);
    HttpSession session = request.getSession();
    String userName = (String) session.getAttribute("userName");
    ModelAndView mav = new ModelAndView();
    String fileFlag;
    Integer total;
    pageBean = getCurrentPage(page);

    fileFlag = "1";// 回收站文件集合
    total = diskFileService.getCount(fileFlag, userName);
    request.setAttribute("mainPage", "recoveryList.jsp");
    diskFileList = diskFileService.findDiskFileList(userName, "", pageBean, fileFlag);
    pageCode = PageUtil.genPaginationNoParam("/disktalk/file/recoveryList", total, pageBean.getPage(),
            pageBean.getPageSize());
    logger.info("===FileController====list===" + diskFileList + "   =====pageCode=" + pageCode);
    System.out.println("=========文件的大小：" + diskFileList.size() + "  total:" + total);
    mav.addObject("diskFileList", diskFileList);
    mav.addObject("pageCode", pageCode);
    mav.setViewName(viewName);
    return mav;
  }

  /**
   * 删除文件
   *
   * @param ids
   * @return
   * @throws Exception
   */
  @RequestMapping(value = "/delete")
  public ModelAndView deleteFile(@RequestParam(value = "ids", required = false) String ids) throws Exception {
    ModelAndView mav = new ModelAndView();
    mav.setViewName(viewName);
    System.out.println("=========deleteFile=========" + ids);
    JSONObject result = new JSONObject();
    request.setAttribute("mainPage", "newFile.jsp");
    String[] id = ids.split(",");
    int count = 0;
    for (int i = 0; i < id.length; i++) {
      diskFile = diskFileService.findDiskFile(id[i]);
      if ("1".equals(diskFile.getFileFlag())) {// 对文件进行删除
        String groupName = diskFile.getDfsGroupName();
        String fileUrl = diskFile.getFileUrl();
        String uuid = diskFile.getUuid();
        boolean dfsFlag = diskFileService.Delete(groupName, fileUrl, uuid);// 删除文件服务器中的存储文件
        if (dfsFlag) {
          boolean sqlDel = diskFileService.delDiskFile(uuid); // 删除数据库中的存储文件
          if (sqlDel) {
            count++;
            if (count == id.length) {
              result.put("result", "文件删除成功！！！");
            }
          } else {
            result.put("result", "文件删除失败！！！");
          }

        } else {
          result.put("result", "文件删除失败！！！");
        }
      } else if ("2".equals(diskFile.getFileFlag())) {
        boolean sqlDel = diskFileService.delDiskFile(diskFile.getUuid()); // 删除数据库中的存储文件
        if (sqlDel) {
          result.put("result", "分享文件已成功删除！！！");
        }
      } else {// 把文件移动到"回收站"
        String fileFlag = "1";
        boolean flag = diskFileService.updateFileRestore(id[i], fileFlag);// 把文件移动到回收站
        if (!flag) {
          diskFile = diskFileService.findDiskFile(id[i]);
          String fileName = diskFile.getFileName();
          result.put("result", fileName + "操作失败！！！");
          ResponseUtil.write(result, response);
          return mav;
        } else {
          count++;
          if (count == id.length) {
            result.put("result", "操作成功！须寻回此文件请到回收站中寻找！！！");
          }
        }
      }
    }
    ResponseUtil.write(result, response);
    return mav;
  }

  /**
   * 回收站中的数据还原
   *
   * @param ids
   * @return
   */
  @RequestMapping(value = "/reduction")
  public ModelAndView reduction(@RequestParam(value = "ids", required = false) String ids) {
    ModelAndView model = new ModelAndView();
    String fileFlag = "0";
    boolean flag = diskFileService.updateFileRestore(ids, fileFlag);
    if (flag) {
      return new ModelAndView("redirect:/file/list?id=2");
    }
    model.setViewName(viewName);
    return model;
  }

  /**
   * 获得用户的文件列表，降序排列
   *
   * @return
   */
  @RequestMapping(value = "/index")
  public ModelAndView fileUploadIndex(HttpServletRequest request) {
    System.out.println("=======fileUploadIndex========");
    ModelAndView model = new ModelAndView();
    request.setAttribute("mainPage", "uploadFile.jsp");
    model.setViewName("main_userCenter");
    return model;
  }

  /**
   * 文件上传
   *
   * @param request
   * @param response
   * @return
   * @throws Exception
   */
  @RequestMapping(value = "/upload")
  public void uploadFile(@RequestParam(value = "page", required = false) String page, HttpServletRequest request,
                         HttpServletResponse response) throws Exception {
    System.out.println("=======uploadFile========");
    HttpSession session = request.getSession();
    boolean flag = diskFileService.uploadFile(request);
    if (flag) {
      System.out.println("文件上传成功！！！");
    } else {
      System.out.println("文件上传失败！！！");
      session.setAttribute("errorInfo", "文件上传失败！！！");
    }
    String ipLocal = new GetIpAddress().getLocalIp();
    StringBuffer hql = new StringBuffer("http://");
    hql.append(ipLocal + ":8080/disktalk/file/list");
    System.out.println("======upload=====" + hql.toString());
    response.sendRedirect(hql.toString());
  }

  /**
   * 文件下载
   *
   * @param ids
   * @return
   * @throws Exception
   */
  @RequestMapping(value = "/download")
  public ResponseEntity<byte[]> downloadFile(@RequestParam(value = "ids", required = false) String ids)
          throws Exception {
    System.out.println("=========downloadFile=========" + ids);
    diskFile = diskFileService.findDiskFile(ids);
    String groupName = diskFile.getDfsGroupName();
    String fileUrl = diskFile.getFileUrl();
    String fileName = diskFile.getFileName();
    System.out.println("==fileUrl===" + fileUrl + " ====groupName==" + groupName + " ====fileName====" + fileName);
    fileUrl = fileUrl.substring(fileName.lastIndexOf("\\") + 1);
    ResponseEntity<byte[]> responseEntity = DiskFileService.download(groupName, fileUrl, fileName);
    updateDownloadSum(responseEntity, diskFile);
    return responseEntity;
  }

  /**
   * 分享文件下载
   *
   * @param ids
   * @return
   * @throws Exception
   */
  @RequestMapping(value = "/shareDownload")
  public ResponseEntity<byte[]> shareDownloadFile(@RequestParam(value = "ids", required = false) String ids)
          throws Exception {
    System.out.println("=========shareDownload=========" + ids);
    String pwd = request.getParameter("pwd");
    System.out.println("==pwd===" + pwd);
    diskFile = diskFileService.findDiskFile(ids);
    if (diskFile.getDownloadPwd().equals(pwd)) {
      String groupName = diskFile.getDfsGroupName();
      String fileUrl = diskFile.getFileUrl();
      String fileName = diskFile.getFileName();
      System.out.println(
              "==fileUrl===" + fileUrl + " ====groupName==" + groupName + " ====fileName====" + fileName);
      fileUrl = fileUrl.substring(fileName.lastIndexOf("\\") + 1);
      ResponseEntity<byte[]> responseEntity = DiskFileService.download(groupName, fileUrl, fileName);
      updateDownloadSum(responseEntity, diskFile);
      return responseEntity;
    }
    return null;
  }

  /**
   * 文件下载  修改下载数量
   *
   * @param responseEntity
   * @param diskFile
   */
  private void updateDownloadSum(ResponseEntity<byte[]> responseEntity, DiskFile diskFile) {
    if (responseEntity.ok() != null) {
      Integer sum = diskFile.getDownloadNum();
      diskFile.setDownloadNum(sum + 1);
      diskFileService.updateFile(diskFile);
    }
  }

  /**
   * 获得初始化页面
   *
   * @param page
   * @return
   */
  private static PageBean getCurrentPage(String page) {
    if (StringUtil.isEmpty(page)) {
      page = "1";
    }
    PageBean pageBean = new PageBean(Integer.parseInt(page), 10);
    return pageBean;
  }

  /**
   * 获得用户名
   *
   * @param request
   * @return
   */
  private static String getUserName() {
    HttpSession session = request.getSession();
    String userName = (String) session.getAttribute("userName");
    return userName;
  }

  /**
   * 生成随机的分享秘密
   *
   * @param length
   * @return
   */
  public static String getRandomString(int length) { // length表示生成字符串的长度
    String base = "abcdefghijklmnopqrstuvwxyz0123456789";
    Random random = new Random();
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < length; i++) {
      int number = random.nextInt(base.length());
      sb.append(base.charAt(number));
    }
    return sb.toString();
  }


  /**
   * 加密解密算法 执行一次加密，两次解密
   *
   * @param inStr
   * @return
   */
  public static String convertMD5(String inStr) {

    char[] a = inStr.toCharArray();
    for (int i = 0; i < a.length; i++) {
      a[i] = (char) (a[i] ^ 't');
    }
    String s = new String(a);
    return s;

  }

  /**
   * 用户登录
   *
   * @param userName
   * @param password
   * @param request
   */
  @RequestMapping("/login")
  public void login(@RequestParam(value = "userName", required = false) String userName,
                    @RequestParam(value = "password", required = false) String password, @RequestParam(value = "token", required = false) String token, HttpServletRequest request) {
    HttpSession session = request.getSession();
    System.err.println("999999999999999999999999999999999999");
    //boolean flag = diskUserService.userLogin(userName, password);
    /*if (flag) {
			session.setAttribute("loginName", userName);
		}*/
  }

}
